#!/bin/bash
#ddddddddddddddddddddddddddddddddddd
#bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
log_file="rpi2_manufacture_result.log"

#If modify it to false, we will use 8bit, no parity.
enable_7bit_even=true
save_stty_settings=`stty -F /dev/ttyAMA0 -g`

cut_off_line="---------------------------"

create_log_file()
{
    if [ -e $log_file ];then
        rm $log_file
    fi

    touch $log_file
}

echotolog()
{
    echo $1 >> $log_file
}

create_log_head()
{
    echotolog "begin rpi2 manufacture test"
    echotolog "------------------------------------------"
    echotolog
}

handle_test_result()
{
    local result="Failed"
    local head="Reason"

    local handled=$1
    shift

    if [ $handled -eq 0 ];then
       result="Successful"
       head="Result"
       ./rpi2_send_result_to_pc.sh $@
    else
       ./rpi2_send_result_to_pc.sh NACK
    fi

    shift

    echotolog "cmd excute $result"
    echotolog "$head: $*"
}

redirect_stderr()
{
        exec 6>&2
        exec 2>> $log_file
}

recover_stderr()
{
        exec 2>&6 6>&-
}

create_log_file;
create_log_head;
redirect_stderr;

stty -echo

if [ "$enable_7bit_even" == "true" ];then
    stty -F /dev/ttyAMA0 evenp
fi

stty -F /dev/ttyAMA0 -onlcr

while true
do
     read cmd
     
     echotolog "received cmd: $cmd"
     echotolog $cut_off_line

     if [ "$cmd" == "QUIT" ];then
        break
     fi

     case "$cmd" in
         "GPIO" )
             excute_result=`./rpi2_gpiotest.sh`
         ;;
         "H_USB" )
             excute_result=`./rpi2_usbtest.sh 4`
         ;;
         "OTP" )
             excute_result=`./rpi2_otptest.sh`
         ;;
         "Ethernet" )
             excute_result=`./rpi2_ethernettest.sh`
         ;;
         "HDMI" )
             excute_result=`./rpi2_hdmitest.sh`
         ;;
         "LED" )
             excute_result=`./rpi2_ledtest.sh`
         ;;
         "Audio" )
             excute_result=`./rpi2_audiotest.sh`
         ;;
         "CPUID" )
             excute_result=`./rpi2_cpuidtest.sh`
         ;;
         "READY" )
             handle_test_result 0 ACK
             continue
         ;;
         * )
             excute_result=`./rpi2_not_validate_cmd.sh`
         ;;
     esac
     handle_test_result $? $cmd $excute_result     
     echotolog
done

stty -F /dev/ttyAMA0 $save_stty_settings

recover_stderr;

stty echo

exit 0
